import logging
import os

from django.conf import settings
from django.contrib import admin, messages
from django.http import HttpResponseRedirect
from django.utils.safestring import mark_safe
from wxmp.wxmp_utils import ExecJs

from mars.utils.common import read_yaml_config

from .models import AliConfig, FuncPrice, MiniAppConfig, WechatConfig

# Register your models here.
# 获取在配置文件中定义的logger，用来记录日志
logger = logging.getLogger("django")


class BaseAdmin(admin.ModelAdmin):
    # 记录条数
    total = 0
    # 控制增加、删除按钮
    def has_add_permission(self, request):
        return self.total == 0

    def has_delete_permission(self, request, obj=None):
        return self.total > 1

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        self.total = len(queryset)
        return queryset


@admin.register(WechatConfig)
class WechatConfigAdmin(BaseAdmin):
    """小程序admin管理界面配置"""

    actions = ["upload_mp"]
    # 需要显示的字段信息
    list_display = ("id", "app_id", "app_secret", "mch_id")

    # 设置哪些字段可以点击进入编辑界面，默认是第一个字段
    list_display_links = ("id", "app_id")

    def receive_upload_info(self, info, request):

        if info.find("done: upload") > 0:
            self.message_user(request, "上传成功", messages.SUCCESS)
        else:
            logger.error(info, exc_info=False)
            self.message_user(request, "上传失败,详细信息请查看日志", messages.ERROR)

    def upload_mp(self, request, queryset):
        ids = ""
        for obj in queryset:
            ids = ids + "{},".format(obj.id)
        return HttpResponseRedirect("/echo/?ids={}".format(ids))

    upload_mp.short_description = "上传小程序"


@admin.register(MiniAppConfig)
class AppConfigAdmin(BaseAdmin):
    """小程序前端配置"""


    # 列表显示字段
    list_display = (
        "id",
        "app_name",
        "share_title",
        "share_path",
        "share_img_thumb",
        "wait_text",
        "wait_logo",
    )
    # 可点击进入编辑界面字段
    list_display_links = ("app_name",)

    def share_img_thumb(self, obj):
        if obj.share_img:
            return mark_safe('<img src="%s" width="100px" />' % obj.share_img.url)

    share_img_thumb.short_description = "分享图片"
    share_img_thumb.allow_tags = True


@admin.register(AliConfig)
class AliConfigAdmin(BaseAdmin):
    """阿里云admin管理界面配置"""

    # 需要显示的字段信息
    list_display = (
        "id",
        "accesskey_id",
        "accesskey_secret",
        "endpoint",
        "bucket_name",
        "region",
    )
    # 设置哪些字段可以点击进入编辑界面，默认是第一个字段
    list_display_links = (
        "id",
        "accesskey_id",
    )


@admin.register(FuncPrice)
class FuncPriceAdmin(BaseAdmin):
    list_display = (
        "id",
        "make_idphoto",
        "change_bg",
        "clip_photo",
        "compress_photo",
        "human_style",
    )
    # 设置哪些字段可以点击进入编辑界面，默认是第一个字段
    list_editable = (
        "make_idphoto",
        "change_bg",
        "clip_photo",
        "compress_photo",
        "human_style",
    )

# 自定义数据库管理界面
class DbManager(type):
    class Meta:
        verbose_name = '数据库管理'
        model_name = 'dbmanager'
        app_label = 'systems'
        abstract = False
        swapped = False
        app_config = False
        verbose_name_plural = verbose_name
        object_name = 'dbmanager'

    _meta = Meta


@admin.register(DbManager)
class DbManagerAdmin(admin.ModelAdmin):
    def changelist_view(self, request, extra_content=None):
        from .views import dbmanager
        return dbmanager(request)


# 通过配置文件增加host,以便部署
yaml_cfg = read_yaml_config(os.path.join(settings.BASE_DIR, "config/host.yml"))

system_name = yaml_cfg.get('system',{}).get('name',"即刻证件照管理后台")
admin.site.site_header = system_name
admin.site.site_title = system_name
admin.site.index_title = system_name
